const { getUserInfo, saveUserInfo } = require('../../utils/user.js')
const { getApiUrl } = require('../../config/config.js')

Page({
  data: {
    userInfo: wx.getStorageSync('userInfo') || {}
  },

  onLoad() {
    // 获取缓存的用户信息
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo) {
      // 确保有gender字段
      if (userInfo.gender === undefined || userInfo.gender === null) {
        userInfo.gender = 1; // 默认为男性
      }
      this.setData({ userInfo })
    }
  },

  // 选择头像
  chooseAvatar() {
    wx.showActionSheet({
      itemList: ['查看头像', '更换头像'],
      success: (res) => {
        if (res.tapIndex === 0) {
          // 查看头像
          this.previewAvatar()
        } else {
          // 更换头像
          this.uploadAvatar()
        }
      }
    })
  },

  // 预览头像
  previewAvatar() {
    const avatar = this.data.userInfo?.avatar
    if (!avatar) return
    
    wx.previewImage({
      urls: [avatar]
    })
  },

  // 上传头像
  uploadAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0]
        
        // 检查文件大小
        wx.getFileInfo({
          filePath: tempFilePath,
          success: (fileInfo) => {
            if (fileInfo.size > 5 * 1024 * 1024) {
              wx.showToast({
                title: '图片大小不能超过5MB',
                icon: 'none'
              })
              return
            }
            
            // 显示上传中的loading
            wx.showLoading({
              title: '上传中...',
              mask: true
            })
            
            // 上传图片
            wx.uploadFile({
              url: getApiUrl('/upload/avatar'),
              filePath: tempFilePath,
              name: 'file',
              formData: {
                userId: this.data.userInfo.id
              },
              header: {
                'token': wx.getStorageSync('token')
              },
              success: (res) => {
                const data = JSON.parse(res.data)
                if (data.code === 200) {
                  // 更新头像URL
                  const newUserInfo = {
                    ...this.data.userInfo,
                    avatar: data.data
                  }
                  
                  // 更新本地存储和页面数据
                  wx.setStorageSync('userInfo', newUserInfo)
                  this.setData({
                    userInfo: newUserInfo
                  })
                  
                  wx.showToast({
                    title: '上传成功',
                    icon: 'success'
                  })
                } else {
                  wx.showToast({
                    title: data.message || '上传失败',
                    icon: 'none'
                  })
                }
              },
              fail: () => {
                wx.showToast({
                  title: '上传失败，请重试',
                  icon: 'none'
                })
              },
              complete: () => {
                wx.hideLoading()
              }
            })
          },
          fail: () => {
            wx.showToast({
              title: '获取文件信息失败',
              icon: 'none'
            })
          }
        })
      }
    })
  },

  // 输入事件处理
  onUsernameInput(e) {
    this.setData({
      'userInfo.username': e.detail.value,
      'userInfo.nickname': e.detail.value
    })
  },

  onPhoneInput(e) {
    this.setData({
      'userInfo.phone': e.detail.value
    })
  },

  onEmailInput(e) {
    this.setData({
      'userInfo.email': e.detail.value
    })
  },

  // 选择性别
  onGenderSelect(e) {
    this.setData({
      'userInfo.gender': parseInt(e.currentTarget.dataset.gender)
    })
  },

  // 个人介绍输入处理
  onBiographyInput(e) {
    this.setData({
      'userInfo.biography': e.detail.value
    })
  },

  // 表单验证
  validateForm() {
    const { username, phone, email } = this.data.userInfo

    if (!username) {
      wx.showToast({
        title: '请输入用户名',
        icon: 'none'
      })
      return false
    }

    if (phone && !/^1[3-9]\d{9}$/.test(phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return false
    }

    if (email && !/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(email)) {
      wx.showToast({
        title: '请输入正确的邮箱',
        icon: 'none'
      })
      return false
    }

    return true
  },

  // 保存资料
  async saveProfile() {
    if (!this.validateForm()) return

    wx.showLoading({ title: '保存中...' })

    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          // url: 'http://localhost:8090/manager/edit',
          url: getApiUrl('/manager/edit'),
          method: 'PUT',
          data: this.data.userInfo,
          header: {
            'token': wx.getStorageSync('token')
          },
          success: resolve,
          fail: reject
        })
      })

      if (res.data.code === 200) {
        const updatedUser = res.data.data
        // 更新本地存储的用户信息
        const userInfo = {
          ...this.data.userInfo,
          username: updatedUser.username,
          nickname: updatedUser.username,
          avatar: updatedUser.avatar,
          phone: updatedUser.phone,
          email: updatedUser.email,
          biography: updatedUser.biography,
          gender: updatedUser.gender,
          updateTime: updatedUser.updateTime
        }
        wx.setStorageSync('userInfo', userInfo)

        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 1500
        })
        
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      }
    } catch (error) {
      console.error('Save profile failed:', error)
      wx.showToast({
        title: '保存失败，请重试',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  }
})
